<template>
  <el-dialog width="66%" :title="dialogTitle" v-model="dialogVisible" modal draggable @close="closeDialog"
    :close-on-click-modal="false" :append-to-body="true">
    <el-form class="dialog-form max-height-form" :model="dynamicValidateForm" ref="vForm" label-position="right"
      label-width="120px" size="medium" :disabled="formDisabled">
      <div v-for="(domain, index) in dynamicValidateForm.domains" :key="domain.defineId"
        :class="['el-col', `el-col-${domain.editFlag === 1 ? domain.singleFlag : ''}`]">
        <el-form-item v-show="domain.editFlag == 1" :prop="'domains.' + index + '.defaultVal'"
          :rules="getValidationRules(domain)">
          <template #label>
            <span>
              <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap">{{
                domain.fieldTitle
              }}</span>
            </span>
          </template>
          <el-input v-if="domain.inputType == 'input'" v-model="domain.defaultVal" clearable
            :disabled="domain.readOnlyFlag == 1" :placeholder="`请输入${domain.fieldTitle}`">
          </el-input>
          <el-select v-else-if="domain.inputType == 'select'" v-model="domain.defaultVal" clearable
            :placeholder="`请选择${domain.fieldTitle}`" :disabled="domain.readOnlyFlag == 1">
            <el-option v-for="item in domain.dictItemList" :key="item.dictItemId" :label="item.itemText"
              :value="item.itemValue" :disabled="item.disabledFlag == 1">
            </el-option>
          </el-select>
          <el-checkbox-group v-model="domain.defaultVal" v-else-if="domain.inputType == 'checkbox'">
            <el-checkbox v-for="e in domain.dictItemList" :key="e.dictItemId" :label="e.itemValue"
              :disabled="domain.readOnlyFlag == 1">
              {{ e.itemText }}
            </el-checkbox>
          </el-checkbox-group>
          <el-radio-group v-model="domain.defaultVal" v-else-if="domain.inputType == 'radio'">
            <el-radio v-for="e in domain.dictItemList" :key="e.dictItemId" :label="e.itemValue">{{
              e.itemText
            }}</el-radio>
          </el-radio-group>
          <el-date-picker v-else-if="domain.inputType == 'date'" v-model="domain.defaultVal"
            :type="domain.fieldName == 'annual' ? 'year' : 'date'"
            :value-format="domain.fieldName == 'annual' ? 'yyyy' : 'yyyy-MM-dd HH:mm:ss'"
            :placeholder="`请选择${domain.fieldTitle}`" :disabled="domain.readOnlyFlag == 1">
          </el-date-picker>
          <el-date-picker v-else-if="domain.inputType == 'time'" v-model="domain.defaultVal" type="datetime"
            :placeholder="`请选择${domain.fieldTitle}`" :disabled="domain.readOnlyFlag == 1">
          </el-date-picker>
        </el-form-item>
      </div>
    </el-form>
    <div v-if="!formDisabled" slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
      <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
      <el-button v-if="type === 'add'" type="primary" @click="saveAndAdd" size="mini">保存并添加下一条</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getInfo, addBox, update } from '@/api/rfid/label'
import { busFieldDefineListBox } from '@/api/sys/field'
import toCamelCase from '@/utils/toCamelCase'
import convertNumberToString from '@/utils/convertNumberToString'
export default {
  name: 'newBoxDialog',
  props: {},

  data() {
    return {
      type: '',
      dialogTitle: '',
      dialogVisible: false,
      formData: {},
      formDisabled: false,
      keepYearsOptions: [],
      dynamicValidateForm: {
        domains: [],
      },
      backupDomains: {}, //备份数据
    }
  },

  created() {
    this.getCustomFields()
  },
  mounted() { },

  methods: {
    getValidationRules(domain) {
      // 定义一个验证规则数组
      const rules = [
        {
          // 是否为必填项
          required: domain.notNullFlag === 1,
          // 触发验证的事件
          trigger: domain.inputType !== 'checkbox' ? ['blur', 'change'] : null,
          // 错误信息
          message: `请输入${domain.fieldTitle}`,
        },
      ]
      // 如果存在验证规则
      if (domain.verifyRule) {
        // 将验证规则添加到规则数组中
        rules.push({
          // 验证规则
          pattern: new RegExp(domain.verifyRule),
          // 错误信息
          message: domain.verifyMsg,
        })
      }

      // 返回验证规则数组
      return rules
    },
    // 获取自定义字段的数据
    getCustomFields() {
      busFieldDefineListBox(1).then((res) => {
        if (res.data.code == 200) {
          // 备份一下数据this.dynamicValidateForm.domains

          this.dynamicValidateForm.domains = res.data.data.map((x) => {
            return {
              ...x,
              fieldName: toCamelCase(x.fieldName),
            }
          })
          // 备份动态验证表单中的domains数据
          this.backupDomains = JSON.parse(JSON.stringify(this.dynamicValidateForm.domains))
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    handleBoxWidth(value) {
      if (value != '') {
        if (value.indexOf('.') > -1) {
          this.formData.boxWidth = value.slice(0, value.indexOf('.') + 3)
        } else {
          this.formData.boxWidth = value
        }
      }
    },
    handlePieceNo(value) {
      // 如果输入值为非数字或小于1，则将其重置为null
      if (isNaN(value) || value < 1) {
        this.formData.pieceNo = null
      } else {
        this.formData.pieceNo = Number(value)
      }
    },
    handlePieceNoBegin(value) {
      // 如果输入值为非数字或小于1，则将其重置为null
      if (isNaN(value) || value < 1) {
        this.formData.pieceNoBegin = null
      } else {
        this.formData.pieceNoBegin = Number(value)
      }
    },
    handlePieceNoEnd(value) {
      // 如果输入值为非数字或小于1，则将其重置为null
      if (isNaN(value) || value < 1) {
        this.formData.pieceNoEnd = null
      } else {
        this.formData.pieceNoEnd = Number(value)
      }
    },
    add() {
      this.formDisabled = false
      this.type = 'add'
      this.dialogTitle = '新建档案盒'
      // 先清空表单数据
      this.formData = {}
      this.dialogVisible = true
    },
    edit(row) {
      this.formDisabled = false
      this.type = 'edit'
      this.dialogTitle = '编辑档案盒'
      getInfo(row.labelId)
        .then((res) => {
          if (res.data.code === 200) {
            const nowRow = convertNumberToString(res.data.data)
            // 遍历data数组
            for (let item of this.dynamicValidateForm.domains) {
              // 检查当前字段名是否存在a对象中
              if (item.fieldName in nowRow) {
                // 如果存在，将defaultVal赋值给a对象的对应键
                item.defaultVal = nowRow[item.fieldName]
                item.labelId = nowRow.labelId
              }
            }

            this.dialogVisible = true
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    // 保存并添加下一条
    saveAndAdd() {
      this.formData = this.dynamicValidateForm.domains.reduce((acc, obj) => {
        acc[obj.fieldName] = obj.defaultVal
        acc.labelId = obj.labelId
        acc.labelType = 1
        return acc
      }, {})
      this.$refs['vForm'].validate((valid) => {
        if (valid) {
          addBox(this.formData)
            .then((res) => {
              if (res.data.code === 200) {
                this.$message.success('建盒成功')
                this.$emit('ok')
                // 清空没有copyFlag标识的数据
                this.dynamicValidateForm.domains = this.dynamicValidateForm.domains.map((item) => {
                  if (item.copyFlag == 1) {
                    item.defaultVal = null
                  }
                  return item
                })
              } else {
                this.$message.warning(res.data.message)
              }
            })
            .catch((err) => {
              this.$message.error(err)
            })
        }
      })
    },
    submitForm() {
      this.formData = this.dynamicValidateForm.domains.reduce((acc, obj) => {
        acc[obj.fieldName] = obj.defaultVal
        acc.labelId = obj.labelId
        acc.labelType = 1
        return acc
      }, {})
      this.$refs['vForm'].validate((valid) => {
        if (valid) {
          if (this.type === 'add') {
            addBox(this.formData)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success('建盒成功')
                  this.closeDialog()
                  this.$emit('ok')
                } else {
                  this.$message.warning(res.data.message)
                }
              })
              .catch((err) => {
                this.$message.error(err)
              })
          } else {
            update(this.formData)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success('修改成功')
                  this.closeDialog()
                  this.$emit('ok')
                } else {
                  this.$message.warning(res.data.message)
                }
              })
              .catch((err) => {
                this.$message.error(err)
              })
          }
        }
      })
    },
    closeDialog() {
      this.$refs['vForm'].resetFields()
      // 关闭弹窗的时候将原数据重新赋值
      this.dynamicValidateForm.domains = this.backupDomains
      this.dialogVisible = false
    },
  },
}
</script>

<style scoped lang="less">
.el-date-editor.el-input {
  width: 100%;
}
</style>
